package com.zl.learning.thread;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class PhaserTest {
    static Random r = new Random();

    private static void millsSleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MarriagePhaser phaser = new MarriagePhaser();
        ExecutorService executorService = Executors.newCachedThreadPool();
        phaser.bulkRegister(7);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new Person(phaser, "p" + i));
        }
        executorService.execute(new Person(phaser, "新郎"));
        executorService.execute(new Person(phaser, "新娘"));
        executorService.shutdown();
    }

    static class MarriagePhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0: {
                    System.out.println("所有人到齐了！" + registeredParties);
                    return false;
                }
                case 1: {
                    System.out.println("所有人吃完了！" + registeredParties);
                    return false;
                }
                case 2: {
                    System.out.println("所有人离开了！" + registeredParties);
                    return false;
                }
                case 3: {
                    System.out.println("婚礼结束，新郎、新娘抱抱！" + registeredParties);
                    return true;
                }
                default:
                    return true;
            }
        }
    }

    static class Person implements Runnable {

        private Phaser phaser;
        private String name;

        public Person(Phaser phaser, String name) {
            this.phaser = phaser;
            this.name = name;
        }

        @Override
        public void run() {
            arrive();
            eat();
            leave();
            hug();
        }

        private void hug() {
            if ("新郎".equals(name) || "新娘".equals(name)) {
                millsSleep();
                System.out.printf("%s 洞房！\n", name);
                phaser.arriveAndAwaitAdvance();
            } else {
                phaser.arriveAndDeregister();
            }
        }

        private void leave() {
            millsSleep();
            System.out.printf("%s 离开！\n", name);
            phaser.arriveAndAwaitAdvance();
        }

        private void eat() {
            millsSleep();
            System.out.printf("%s 吃完！\n", name);
            phaser.arriveAndAwaitAdvance();
        }

        private void arrive() {
            millsSleep();
            System.out.printf("%s 到达现场！\n", name);
            phaser.arriveAndAwaitAdvance();
        }
    }
}
